package com.runa.monitor.platinterface.extend.third.newester.service;


import com.alibaba.fastjson.JSONObject;
import com.runa.protocol.util.UtilTime;
import com.runa.monitor.platinterface.extend.third.controller.ThirdPartOfMeterController;
import com.runa.monitor.platinterface.extend.third.newester.pojo.AjaxResponse;
import com.runa.monitor.platinterface.extend.third.newester.pojo.NetEquDockingDataVo;
import com.runa.monitor.platinterface.extend.third.newester.pojo.ResponseCode;
import com.runa.monitor.platinterface.extend.third.newester.util.CheckUtil;
import com.runa.monitor.platinterface.extend.third.newester.vo.*;
import com.runa.monitor.platinterface.extend.third.pojo.Result;
import com.runa.monitor.platinterface.extend.third.vo.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class EquDockingDataService {
    private static final Logger logger = LoggerFactory.getLogger(EquDockingDataService.class);

    @Resource
    private ThirdPartOfMeterController thirdPartOfMeterController;
//    @Resource
//    private EquDockingDataClient equDockingDataClient;
//    @Resource
//    private EquOutFeignClient equOutFeignClient;

    private static final String ERROR_CODE = "-1";

    private static final String SUCCESS_CODE = "0";

    public AjaxResponse saveHouseMeterData(List<HouseMeterDockingDetailVo> detailVoList) {
        List<DockingDataResponseVo> responseVoList = new ArrayList<>();
        List<HouseMeterDockingDataVo> houseMeterDockingDataVos = new ArrayList<>();
        for (HouseMeterDockingDetailVo detailVo : detailVoList) {
            logger.info("------收到外部户表实时数据：{}", JSONObject.toJSONString(detailVo));
            String errorMsg = CheckUtil.checkObjectParam(detailVo);
            if (StringUtils.isNotBlank(errorMsg)) {
                DockingDataResponseVo dockingDataResponseVo = new DockingDataResponseVo();
                dockingDataResponseVo.setReason(errorMsg);
                dockingDataResponseVo.setFieldCode(ERROR_CODE);
                dockingDataResponseVo.setMeterSerialNo(detailVo.getMeterSerialNo());
                dockingDataResponseVo.setNetEquSerialNo(detailVo.getNetEquSerialNo());
                responseVoList.add(dockingDataResponseVo);
            } else {
                HouseMeterDockingDataVo dataVo = new HouseMeterDockingDataVo();
                dataVo.setSerialNo(detailVo.getMeterSerialNo());
                dataVo.setNetEquSerialNo(detailVo.getNetEquSerialNo());
                dataVo.setState("1".equals(detailVo.getState()));
                dataVo.setReason(detailVo.getReason());
                dataVo.setPlanTime(UtilTime.StringToDate(detailVo.getPlanTime(), "yyyy-MM-dd HH:mm:ss"));
                String readTime = detailVo.getReadTime();
                if (StringUtils.isNotBlank(readTime)) {
                    dataVo.setReadTime(UtilTime.StringToDate(readTime, "yyyy-MM-dd HH:mm:ss"));
                }
                String equTime = detailVo.getEquTime();
                if (StringUtils.isNotBlank(equTime)) {
                    dataVo.setEquTime(UtilTime.StringToDate(equTime, "yyyy-MM-dd HH:mm:ss"));
                }
                dataVo.setFlow(detailVo.getFlow());
                dataVo.setHeat(detailVo.getHeat());
                dataVo.setAccFlow(detailVo.getAccFlow());
                dataVo.setAccHeat(detailVo.getAccHeat());
                dataVo.setSupplyTemperature(detailVo.getSupplyTemperature());
                dataVo.setReturnTemperature(detailVo.getReturnTemperature());
                dataVo.setWorkTime(detailVo.getWorkTime());
                dataVo.setBattery(detailVo.getBattery());
                dataVo.setStateCode(detailVo.getStateCode());
                houseMeterDockingDataVos.add(dataVo);
            }
        }
        if (!CollectionUtils.isEmpty(houseMeterDockingDataVos)) {
//            SortUtil<HouseMeterDockingDataVo> sortUtil = new SortUtil("planTime", "asc");
//            houseMeterDockingDataVos = sortUtil.sort(houseMeterDockingDataVos, HouseMeterDockingDataVo.class);
            Result<List<DockingDataResponseVo>> result = thirdPartOfMeterController.batchSaveHouseMeterData(houseMeterDockingDataVos);
            List<DockingDataResponseVo> dockingDataResponseVos = result.getData();
            if (!CollectionUtils.isEmpty(dockingDataResponseVos)) {
                responseVoList.addAll(dockingDataResponseVos);
            }
        }
        if (responseVoList.stream().anyMatch(v -> SUCCESS_CODE.equals(v.getFieldCode()))) {
            logger.info("-----保存上传的户表数据成功------");
            return AjaxResponse.of(responseVoList);
        } else {
            logger.info("-----保存上传的户表数据失败------");
            return AjaxResponse.of(ResponseCode.FAIL, responseVoList);
        }
    }

    public AjaxResponse saveHouseValveData(List<HouseValveDockingDetailVo> detailVoList) {
        List<HouseValveDockingDataVo> valveDockingDataVos = new ArrayList<>();
        List<DockingDataResponseVo> responseVoList = new ArrayList<>();
        for (HouseValveDockingDetailVo detailVo : detailVoList) {
            logger.info("------收到外部户阀实时数据：{}", JSONObject.toJSONString(detailVo));
            String errorMsg = CheckUtil.checkObjectParam(detailVo);
            if (StringUtils.isNotBlank(errorMsg)) {
                DockingDataResponseVo dockingDataResponseVo = new DockingDataResponseVo();
                dockingDataResponseVo.setReason(errorMsg);
                dockingDataResponseVo.setFieldCode(ERROR_CODE);
                dockingDataResponseVo.setMeterSerialNo(detailVo.getMeterSerialNo());
                dockingDataResponseVo.setNetEquSerialNo(detailVo.getNetEquSerialNo());
                responseVoList.add(dockingDataResponseVo);
            } else {
                HouseValveDockingDataVo dataVo = new HouseValveDockingDataVo();
                dataVo.setSerialNo(detailVo.getMeterSerialNo());
                dataVo.setNetEquSerialNo(detailVo.getNetEquSerialNo());
                dataVo.setState("1".equals(detailVo.getState()));
                dataVo.setReason(detailVo.getReason());
                dataVo.setPlanTime(UtilTime.StringToDate(detailVo.getPlanTime(), "yyyy-MM-dd HH:mm:ss"));
                String readTime = detailVo.getReadTime();
                if (StringUtils.isNotBlank(readTime)) {
                    dataVo.setReadTime(UtilTime.StringToDate(readTime, "yyyy-MM-dd HH:mm:ss"));
                }
                String equTime = detailVo.getEquTime();
                if (StringUtils.isNotBlank(equTime)) {
                    dataVo.setEquTime(UtilTime.StringToDate(equTime, "yyyy-MM-dd HH:mm:ss"));
                }
                dataVo.setWorkTime(detailVo.getWorkTime());
                dataVo.setSettingTemperature(detailVo.getSettingTemperature());
                if (null != detailVo.getIsLockTemperature()) {
                    dataVo.setLockTemperature("1".equals(detailVo.getIsLockTemperature()));
                }
                dataVo.setTemperature(detailVo.getTemperature());
                dataVo.setRemainderHeat(detailVo.getRemainderHeat());
                dataVo.setControlType(detailVo.getControlType());
                if (null != detailVo.getSwitchState()) {
                    dataVo.setSwitchState("1".equals(detailVo.getSwitchState()));
                }
                dataVo.setValveOpening(detailVo.getValveOpening());
                dataVo.setStateCode(detailVo.getStateCode());
                valveDockingDataVos.add(dataVo);
            }
        }
        if (!CollectionUtils.isEmpty(valveDockingDataVos)) {
//            SortUtil<HouseValveDockingDataVo> sortUtil = new SortUtil("planTime", "asc");
//            valveDockingDataVos = sortUtil.sort(valveDockingDataVos, HouseValveDockingDataVo.class);
            Result<List<DockingDataResponseVo>> result = thirdPartOfMeterController.batchSaveHouseValveData(valveDockingDataVos);
            List<DockingDataResponseVo> dockingDataResponseVos = result.getData();
            if (!CollectionUtils.isEmpty(dockingDataResponseVos)) {
                responseVoList.addAll(dockingDataResponseVos);
            }
        }
        if (responseVoList.stream().anyMatch(v -> SUCCESS_CODE.equals(v.getFieldCode()))) {
            logger.info("-----保存上传的户阀数据成功------");
            return AjaxResponse.of(responseVoList);
        } else {
            logger.info("-----保存上传的户阀数据成功------");
            return AjaxResponse.of(ResponseCode.FAIL, responseVoList);
        }
    }

    public AjaxResponse saveNetEquData(List<NetEquDockingDetailVo> detailVoList) {
        List<NetEquDockingDataVo> netEquDockingDataVos = new ArrayList<>();
        List<DockingDataResponseVo> responseVoList = new ArrayList<>();
        for (NetEquDockingDetailVo detailVo : detailVoList) {
            logger.info("------收到外部网络设备实时数据：{}", JSONObject.toJSONString(detailVo));
            String errorMsg = CheckUtil.checkObjectParam(detailVo);
            if (StringUtils.isNotBlank(errorMsg)) {
                DockingDataResponseVo dockingDataResponseVo = new DockingDataResponseVo();
                dockingDataResponseVo.setReason(errorMsg);
                dockingDataResponseVo.setFieldCode(ERROR_CODE);
                dockingDataResponseVo.setMeterSerialNo(detailVo.getSerialNo());
                responseVoList.add(dockingDataResponseVo);
            } else {
                NetEquDockingDataVo dataVo = new NetEquDockingDataVo();
                dataVo.setSerialNo(detailVo.getSerialNo());
                dataVo.setState("1".equals(detailVo.getState()));
//                dataVo.setRecentlyTime(detailVo.getRecentlyTime() == null ? new Date() : UtilTime.StringToDate(detailVo.getRecentlyTime(), "yyyy-MM-dd HH:mm:ss") );
//                dataVo.setIccid(detailVo.getIccid());
//                dataVo.setVersion(detailVo.getVersion());
//                dataVo.setBatteryConsumption(detailVo.getBatteryConsumption());
//                dataVo.setSignal(detailVo.getSignal() == null ? null : Double.valueOf(detailVo.getSignal()).intValue());
                netEquDockingDataVos.add(dataVo);
            }
        }
        if (!CollectionUtils.isEmpty(netEquDockingDataVos)) {
//            SortUtil<NetEquDockingDataVo> sortUtil = new SortUtil("recentlyTime", "asc");
//            netEquDockingDataVos = sortUtil.sort(netEquDockingDataVos, NetEquDockingDataVo.class);
            Result<List<DockingDataResponseVo>> result = thirdPartOfMeterController.batchSaveNetEquData(netEquDockingDataVos);
            List<DockingDataResponseVo> dockingDataResponseVos = result.getData();
            if (!CollectionUtils.isEmpty(dockingDataResponseVos)) {
                responseVoList.addAll(dockingDataResponseVos);
            }
        }
        if (responseVoList.stream().anyMatch(v -> SUCCESS_CODE.equals(v.getFieldCode()))) {
            logger.info("-----保存上传的网络设备数据成功------");
            return AjaxResponse.of(responseVoList);
        } else {
            logger.info("-----保存上传的网络设备数据失败------");
            return AjaxResponse.of(ResponseCode.FAIL, responseVoList);
        }
    }

    public AjaxResponse saveTemperaturePanelData(List<TemperaturePanelDockingDetailVo> detailVoList) {
        List<DockingDataResponseVo> responseVoList = new ArrayList<>();
        List<TemperaturePanelDockingDataVo> temperaturePanelDockingDataVos = new ArrayList<>();
        for (TemperaturePanelDockingDetailVo detailVo : detailVoList) {
            logger.info("------收到外部温度面板实时数据：{}", JSONObject.toJSONString(detailVo));
            String errorMsg = CheckUtil.checkObjectParam(detailVo);
            if (StringUtils.isNotBlank(errorMsg)) {
                DockingDataResponseVo dockingDataResponseVo = new DockingDataResponseVo();
                dockingDataResponseVo.setReason(errorMsg);
                dockingDataResponseVo.setFieldCode(ERROR_CODE);
                dockingDataResponseVo.setMeterSerialNo(detailVo.getMeterSerialNo());
                dockingDataResponseVo.setNetEquSerialNo(detailVo.getNetEquSerialNo());
                responseVoList.add(dockingDataResponseVo);
            } else {
                TemperaturePanelDockingDataVo dataVo = new TemperaturePanelDockingDataVo();
                dataVo.setSerialNo(detailVo.getMeterSerialNo());
                dataVo.setNetEquSerialNo(detailVo.getNetEquSerialNo());
                dataVo.setState("1".equals(detailVo.getState()));
                dataVo.setReason(detailVo.getReason());
                dataVo.setPlanTime(UtilTime.StringToDate(detailVo.getPlanTime(), "yyyy-MM-dd HH:mm:ss"));
                String readTime = detailVo.getReadTime();
                if (StringUtils.isNotBlank(readTime)) {
                    dataVo.setReadTime(UtilTime.StringToDate(readTime, "yyyy-MM-dd HH:mm:ss"));
                }
                String equTime = detailVo.getEquTime();
                if (StringUtils.isNotBlank(equTime)) {
                    dataVo.setEquTime(UtilTime.StringToDate(equTime, "yyyy-MM-dd HH:mm:ss"));
                }
                dataVo.setTemperature(detailVo.getTemperature());
                dataVo.setStateCode(detailVo.getStateCode());
                temperaturePanelDockingDataVos.add(dataVo);
            }
        }
        if (!CollectionUtils.isEmpty(temperaturePanelDockingDataVos)) {
//            SortUtil<TemperaturePanelDockingDataVo> sortUtil = new SortUtil("planTime", "asc");
//            temperaturePanelDockingDataVos = sortUtil.sort(temperaturePanelDockingDataVos, TemperaturePanelDockingDataVo.class);
            Result<List<DockingDataResponseVo>> result = thirdPartOfMeterController.batchSaveTemperaturePanelData(temperaturePanelDockingDataVos);
            List<DockingDataResponseVo> dockingDataResponseVos = result.getData();
            if (!CollectionUtils.isEmpty(dockingDataResponseVos)) {
                responseVoList.addAll(dockingDataResponseVos);
            }
        }
        if (responseVoList.stream().anyMatch(v -> SUCCESS_CODE.equals(v.getFieldCode()))) {
            logger.info("-----保存上传的温度面板数据成功------");
            return AjaxResponse.of(responseVoList);
        } else {
            logger.info("-----保存上传的温度面板数据成功------");
            return AjaxResponse.of(ResponseCode.FAIL, responseVoList);
        }
    }

    public AjaxResponse saveTemperaturePressureData(List<TemperaturePressureDockingDetailVo> detailVoList) {
        List<TemperaturePressureDockingDetailVo> dtoS = new ArrayList<>();
        for (TemperaturePressureDockingDetailVo temperaturePressureDockingDetailVo : detailVoList) {
            TemperaturePressureDockingDetailVo dto =
                    new TemperaturePressureDockingDetailVo();
            BeanUtils.copyProperties(temperaturePressureDockingDetailVo, dto);
            dtoS.add(dto);
        }
//        Result result1 = equOutFeignClient.temperaturePressureData(dtoS);
//        logger.info("------热网数据设备数据处理结束：{}", JSONObject.toJSONString(result1.getMessage()));
        List<DockingDataResponseVo> responseVoList = new ArrayList<>();
        List<TemperaturePressureDataDockingDataVo> temperaturePressureDataDockingDataVos = new ArrayList<>();
        for (TemperaturePressureDockingDetailVo detailVo : detailVoList) {
            logger.info("------收到外部温压监测仪实时数据：{}", JSONObject.toJSONString(detailVo));
            String errorMsg = CheckUtil.checkObjectParam(detailVo);
            if (StringUtils.isNotBlank(errorMsg)) {
                DockingDataResponseVo dockingDataResponseVo = new DockingDataResponseVo();
                dockingDataResponseVo.setReason(errorMsg);
                dockingDataResponseVo.setFieldCode(ERROR_CODE);
                dockingDataResponseVo.setMeterSerialNo(detailVo.getMeterSerialNo());
                responseVoList.add(dockingDataResponseVo);
            } else {
                TemperaturePressureDataDockingDataVo dataVo = new TemperaturePressureDataDockingDataVo();
                dataVo.setSerialNo(detailVo.getMeterSerialNo());
                dataVo.setState("1".equals(detailVo.getState()));
                dataVo.setReason(detailVo.getReason());
                dataVo.setPlanTime(UtilTime.StringToDate(detailVo.getPlanTime(), "yyyy-MM-dd HH:mm:ss"));
                String readTime = detailVo.getReadTime();
                if (StringUtils.isNotBlank(readTime)) {
                    dataVo.setReadTime(UtilTime.StringToDate(readTime, "yyyy-MM-dd HH:mm:ss"));
                }
                BigDecimal supplyPressure = detailVo.getSupplyPressure();
                BigDecimal returnPressure = detailVo.getReturnPressure();
                //客户对接的第三方传值是kmp，所以我们不用乘以1000了，标准的对外接口文档的单位也是kmp
/*                if (supplyPressure !=null && supplyPressure.compareTo(BigDecimal.ZERO) > 0) {
                if (supplyPressure != null && supplyPressure.compareTo(BigDecimal.ZERO) > 0) {
                    supplyPressure = supplyPressure.multiply(new BigDecimal("1000"));
                }
                if (returnPressure != null && returnPressure.compareTo(BigDecimal.ZERO) > 0) {
                    returnPressure = returnPressure.multiply(new BigDecimal("1000"));
                }*/
                dataVo.setSupplyTemperature(detailVo.getSupplyTemperature());
                dataVo.setReturnTemperature(detailVo.getReturnTemperature());
                dataVo.setSupplyPressure(supplyPressure);
                dataVo.setReturnPressure(returnPressure);
                dataVo.setBatteryPressure(detailVo.getBatteryPressure());
                dataVo.setStateCode(detailVo.getStateCode());
                dataVo.setSignal(detailVo.getSignal());
                temperaturePressureDataDockingDataVos.add(dataVo);
            }
        }
        if (!CollectionUtils.isEmpty(temperaturePressureDataDockingDataVos)) {
//            SortUtil<TemperaturePressureDataDockingDataVo> sortUtil = new SortUtil("planTime", "asc");
//            temperaturePressureDataDockingDataVos = sortUtil.sort(temperaturePressureDataDockingDataVos, TemperaturePressureDataDockingDataVo.class);
            Result<List<DockingDataResponseVo>> result = thirdPartOfMeterController.batchSaveTemperaturePressureData(temperaturePressureDataDockingDataVos);
            List<DockingDataResponseVo> dockingDataResponseVos = result.getData();
            if (!CollectionUtils.isEmpty(dockingDataResponseVos)) {
                responseVoList.addAll(dockingDataResponseVos);
            }
        }
        if (responseVoList.stream().anyMatch(v -> SUCCESS_CODE.equals(v.getFieldCode()))) {
            logger.info("-----保存上传的温压监测仪数据成功------");
            return AjaxResponse.of(responseVoList);
        } else {
            logger.info("-----保存上传的温压监测仪数据失败------");
            return AjaxResponse.of(ResponseCode.FAIL, responseVoList);
        }
    }

    public CheckResultList saveStationMeterData(StationMeterListVO in) {
        CheckResultList checkResultList = new CheckResultList();
        List<StationMeterCurrentDataVO> currentDataInfo = in.getCurrentDataInfo();
        List<DockingDataResponseVo> responseVoList = new ArrayList<>();
        List<StationMeterDataDockingDataVo> stationMeterDataDockingDataVos = new ArrayList<>();

        for (StationMeterCurrentDataVO detailVo : currentDataInfo) {
            logger.info("------收到换热站实时数据：{}", JSONObject.toJSONString(detailVo));
            String errorMsg = CheckUtil.checkObjectParam(detailVo);
            if (StringUtils.isNotBlank(errorMsg)) {
                DockingDataResponseVo dockingDataResponseVo = new DockingDataResponseVo();
                dockingDataResponseVo.setReason(errorMsg);
                dockingDataResponseVo.setFieldCode(ERROR_CODE);
                dockingDataResponseVo.setMeterSerialNo(detailVo.getMeterSerialNo());
                responseVoList.add(dockingDataResponseVo);
            } else {
                StationMeterDataDockingDataVo dataVo = new StationMeterDataDockingDataVo();
                dataVo.setMeterSerialNo(detailVo.getMeterSerialNo());
                dataVo.setNetEquSerialNo(detailVo.getNetEquSerialNo());
                dataVo.setReason(detailVo.getReason());
                dataVo.setState("1".equals(detailVo.getState()));
                String planTime = detailVo.getPlanTime();
                if (StringUtils.isNotBlank(planTime)) {
                    dataVo.setPlanTime(UtilTime.StringToDate(planTime, "yyyy-MM-dd HH:mm:ss"));
                }
                String readTime = detailVo.getReadTime();
                if (StringUtils.isNotBlank(readTime)) {
                    dataVo.setReadTime(UtilTime.StringToDate(detailVo.getReadTime(), "yyyy-MM-dd HH:mm:ss"));
                }
                String equTime = detailVo.getEquTime();
                if (StringUtils.isNotBlank(equTime)) {
                    dataVo.setEquTime(UtilTime.StringToDate(equTime, "yyyy-MM-dd HH:mm:ss"));
                }
                dataVo.setFlow(detailVo.getFlow());
                dataVo.setHeat(detailVo.getHeat());
                dataVo.setAccFlow(detailVo.getAccFlow());
                dataVo.setAccHeat(detailVo.getAccHeat());
                dataVo.setSupplyTemperature(detailVo.getSupplyTemperature());
                dataVo.setReturnTemperature(detailVo.getReturnTemperature());
                dataVo.setStateCode(detailVo.getStateCode());
                dataVo.setWorkTime(detailVo.getWorkTime());
                dataVo.setBattery(detailVo.getBattery());
                stationMeterDataDockingDataVos.add(dataVo);
            }
        }
        if (!CollectionUtils.isEmpty(stationMeterDataDockingDataVos)) {
//            SortUtil<StationMeterDataDockingDataVo> sortUtil = new SortUtil("planTime", "asc");
//            stationMeterDataDockingDataVos = sortUtil.sort(stationMeterDataDockingDataVos, StationMeterDataDockingDataVo.class);
            Result<List<DockingDataResponseVo>> result = thirdPartOfMeterController.batchSaveStationMeterData(stationMeterDataDockingDataVos);
            List<DockingDataResponseVo> dockingDataResponseVos = result.getData();
            if (!CollectionUtils.isEmpty(dockingDataResponseVos)) {
                responseVoList.addAll(dockingDataResponseVos);
            }
        }
        if (responseVoList.stream().anyMatch(v -> SUCCESS_CODE.equals(v.getFieldCode()))) {
            logger.info("-----保存上传的站表数据成功------");
            checkResultList.setResultInfo(responseVoList);
            checkResultList.setCode(0);
            return checkResultList;
        } else {
            logger.info("-----保存上传的站表数据失败------");
            checkResultList.setResultInfo(responseVoList);
            checkResultList.setCode(40002);
            return checkResultList;
        }
    }
}
